/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package parser.nodes;

import codegen.AbstractDescr;
import codegen.CodeGen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import parser.Pair;

public class IfStatementNode extends Node {

	private ExpressionNode condition;
	private StatementSequenceNode thenPart, elsePart;
	private List<Pair<ExpressionNode, StatementSequenceNode>> elseifs = new ArrayList<>();

	public IfStatementNode(ExpressionNode condition, StatementSequenceNode thenPart) {
		this.condition = condition;
		this.thenPart = thenPart;
	}

	public void setElse(StatementSequenceNode elsePart) {
		this.elsePart = elsePart;
	}

	public void addElseIf(ExpressionNode condition, StatementSequenceNode stmts) {
		elseifs.add(new Pair<>(condition, stmts));
	}

	@Override
	public void compile(CodeGen c) throws CompileError {
		c.outstr("//if");
		condition.compile(c);
		int elseLabel = c.getLabel();
		c.outstr("BF, " + elseLabel);
		thenPart.compile(c);
		int afterElse = c.getLabel();
		c.outstr("JMP, " + afterElse);
		c.outstr("LABEL, " + elseLabel);

		for (Pair<ExpressionNode, StatementSequenceNode> pair : elseifs) {
			int elseifLabel = c.getLabel();
			pair.getFirst().compile(c);
			c.outstr("BF, " + elseifLabel);
			pair.getSecond().compile(c);
			c.outstr("JMP, " + afterElse);
			c.outstr("LABEL, " + elseifLabel);
		}
		if (elsePart != null)
			elsePart.compile(c);
		c.outstr("LABEL, " + afterElse);
	}

	;

    @Override
	public void print() {
		p("IfStatement:");
		indent();
		p("IF");
		condition.print();
		p("THEN");
		thenPart.print();

		for (Pair<ExpressionNode, StatementSequenceNode> elseif : elseifs) {
			p("ELSIF");
			elseif.getFirst().print();
			p("THEN");
		}

		if (elsePart != null) {
			p("ELSE");
			elsePart.print();
		}
		p("END");
		unindent();
	}

	@Override
	public void abstractPrint() {
		p("IF");
		indent();
		condition.abstractPrint();
		indent();
		thenPart.abstractPrint();
		unindent();
		for (Pair<ExpressionNode, StatementSequenceNode> elseif : elseifs) {
			elseif.getFirst().abstractPrint();
			indent();
			elseif.getSecond().abstractPrint();
			unindent();
		}
		if (elsePart != null) {
			elsePart.abstractPrint();
		}
		unindent();
	}
}
